/**
 * Created by jiachenpan on 16/11/18.
 */
import request from '@/utils/request'

export default {
	getList(fetchList, obj){
		obj.listLoading = true
		fetchList(obj.listQuery).then(response => {
			obj.listLoading = false
			obj.list = response.data.data
			obj.total = response.meta.pagination.total
		})
	},
	handleEdit(type, row, obj){
		if(row){
			obj.temp=row;
		}else{
			obj.temp=obj.getDefaultTemp();
		}

		obj.dialogStatus = type
		obj.dialogFormVisible = true
		obj.$nextTick(() => {
			obj.$refs['dataForm'].clearValidate()
		})
	},
	handleDelete(resource, row, obj){		
        obj.$alert(obj.$t('table.deleteMsg'), obj.$t('table.delete'), {
          confirmButtonText:  obj.$t('table.confirm'),
          callback: action => {
            this.deleteResource(resource,row.id).then(()=>{
              obj.$notify({
                title: 'Success',
                message: 'Item deleted',
                type: 'success',
                duration: 2000
              })
              const index = obj.list.indexOf(row)
              obj.list.splice(index, 1)
            })
          }
        });
	},
	deleteResource(resource, id){
		return request({
			url: '/admin/'+resource+'/'+id,
			method: 'delete'
		})
	},
	updateResource(resource,row,obj){
		let url,method;
		if(row.id){
			url='/admin/'+resource+'/'+row.id
			method='put'
		}else{
			url='/admin/'+resource
			method='post'
		}
		request({
				url: url,
				method: method,
				params: row
		}).then(()=>{
			obj.dialogFormVisible=false
			obj.getList()
		})
	},

	handleSortChange(data,obj){
		const { prop, order } = data
		if (order === 'ascending') {
			obj.listQuery.sort = '+'
		} else {
			obj.listQuery.sort = '-'
		}
		obj.listQuery.sort += prop
		obj.listQuery.page = 1
		obj.getList()
	},

	setTabQuery(options,field,obj){
		options.forEach(item=>{
			if(item.label==obj.activeName){
				obj.listQuery[field]=item.value
			}
		})
	}
}